package com.sys.basics.config.socketio.nameSpaceListener;

import com.corundumstudio.socketio.*;
import com.corundumstudio.socketio.protocol.Packet;
import com.corundumstudio.socketio.protocol.PacketType;
import com.corundumstudio.socketio.store.RedissonStoreFactory;
import com.corundumstudio.socketio.store.pubsub.DispatchMessage;
import com.corundumstudio.socketio.store.pubsub.PubSubStore;
import com.corundumstudio.socketio.store.pubsub.PubSubType;
import com.sys.basics.config.socketio.data.DispatchData;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Slf4j
@Component
public abstract class AbstractEventLintener {
    @Autowired
    private NameSpaceEventListenerMgr nameSpaceEventListenerMgr;

    @Autowired
    protected RedissonClient redissonClient;

    @Autowired
    protected RedissonStoreFactory socketIoStoreFactory;

    @Autowired
    protected PubSubStore socketIoPubSubStore;

    @Autowired
    protected SocketIOServer nettySocketIOServer;

    /**
     * @author: ares
     * @date: 2021/11/9 11:24
     * @description: 组合packet
     * @param eventName
     * @param nsp
     * @param roomName
     * @param dispatchData
     * @return
     */
    public Packet getPublishPacket(String eventName, String nsp, String roomName, DispatchData dispatchData){
        Packet packet = new Packet(PacketType.MESSAGE);
        packet.setSubType(PacketType.EVENT);
        packet.setName(eventName);
        packet.setData(dispatchData);
        packet.setNsp(nsp);
        return packet;
    }

    /**
     * @author: ares
     * @date: 2021/11/8 14:32
     * @description: 发布消息
     * @param eventName
     * @param nsp
     * @param roomName
     * @param dispatchData
     */
    public void publish(String eventName, String nsp, String roomName, DispatchData dispatchData){
        Packet packet = getPublishPacket(eventName, nsp, roomName, dispatchData);
        socketIoPubSubStore.publish(PubSubType.DISPATCH, new DispatchMessage(nsp, packet, roomName));
    }

    /**
     * @author: ares
     * @date: 2021/11/9 11:09
     * @description: 收到订阅数据
     * @param msg
     */
    public void onSubscribeMessage(DispatchMessage msg) {
        Packet packet = msg.getPacket();
        DispatchData dispatchData = packet.getData();
        Long consumerId = dispatchData.getConsumerId();
        HashMap<String, InterfaceEventListener> nameSpaceListener = nameSpaceEventListenerMgr.getNameSpaceListener();
        nameSpaceListener.forEach((nsp, listener)->{
            if(consumerId == null){
                listener.sendEventToClients(msg);
            }else {
                listener.sendEventToClient(msg);
            }
        });
    }
}
